<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		<button type="primary" @tap="messageSend">发送 Protobuf 序列数据</button>
	</view>
</template>

<script>
	
	// 引入生成的 Protobuf 代码
	import {imooc} from '../../proto/proto.js';
		
	
	export default {
		data() {
			return {
				title: '充电桩微信小程序 Demo',
				//socket对象
				sockeTask: null,
				//websocket通道是否已打开
				is_socket_open: false
			}
		},
		mounted() {
			
			
		},
		onLoad() {
			
			//WebSocket初始化
			this.webSocketInit();

		},
		methods: {
		
			
			//WebSocket初始化
			webSocketInit() {
				//=============== 使用uni封装的websocket ===============//
				
				//创建连接
				this.socketTask = uni.connectSocket({
					//demo连接地址
					// url: 'ws://127.0.0.1:8085/ws/server',
					
					//NettyServer连接地址
					url: 'ws://127.0.0.1:8989/ws',
					header: {
					    'content-type': 'application/json'
							// "Content-Type": "application/octet-stream"
					}, 
					success: () => {
						console.log("imooc WebSocket创建成功");
						
					},
					fail:() => {
						console.log("imooc WebSocket创建失败");
					},
					
					
				
				})
				
				
				
				//监听websocket打开事件
				this.socketTask.onOpen((res)=>{
					
					this.is_socket_open = true;
					console.log('imooc WebSocket连接已打开！'); 
					
					// this.socketTask.send({
					// 	data: "这是小程序成功连接Netty测试发送的信息",
					// 	async success() {
					// 		console.log("消息发送成功")
					// 	},
					// })
					
				});
				
				
				//监听websocket关闭事件
				this.socketTask.onClose((res)=>{
					this.is_socket_open = false;
					console.log("imooc WebSocket已关闭");
				})
				
				
				//监听websocket通道接收消息
				this.socketTask.onMessage((res) => {
					
					console.log("收到Netty服务端内容："+res.data);
				});
				
				
				
				
								
				
				//监听错误
				uni.onSocketError((res) => {
					console.info("imooc 监听WebSocket错误: " + res.errMsg)
				});
				
				
				
			},
			
			
			//WebSocket发送protobuf消息
			messageSend() {
				
				//检查websocket是否正常连接
				console.log(this.is_socket_open)
				console.log(this.socketTask)
				
				
				if (this.is_socket_open) {
					
					// 创建一个 ChargingCmd 对象
					let cmdData = imooc.ChargingCmd.create({
						cmd: '1: Imooc Start Charge',
						// cmd: '3',
					});
					
					//============ (发送protobuf序列数据) ==================//
					
					//把ChargingCmd对象 编码成Uint8Array (特殊的二进制数据)
					let cmdU8 = imooc.ChargingCmd.encode(cmdData).finish()
					
					//微信小程序不支持Uint8Array，需要将Uint8Array转换为arraybuffer
					let cmdBuffer = Uint8Array.from(cmdU8).buffer;
					
					
					//发送
					this.socketTask.send({
						data: cmdBuffer,
						// data: '测试websocket数据',
						async success() {
							console.log("Protobuf序列数据已发送")
						}
					});
				}else {
					console.log("消息发送失败!")
				}
				
			},
			
			//WebSocket接收消息
			getMessage() {
				
				//检查websocket是否正常连接
				console.log(this.is_socket_open)
				console.log(this.socketTask)
				
				
				
				// if (this.is_socket_open) {
				// 	this.socketTask.onMessage((res) => {
						
				// 		//反序列化接收的protobuf序列数据
				// 		let resBuf = Buffer.from(res.data)
				// 		// let resMessage = imooc.User2.decode(resBuf)
				// 		// let obj = imooc.User2.toObject(loginRspMessage, {
				// 		// 	name: String, 
				// 		// })
						
				// 		console.log("收到服务端内容：" + resBuf);
				// 	});
				// }
				
			}
			
			
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
